<!--
 * @description:
 * @author: huangpeng
 * @date: 2023年09月06日 16:33
 * @Copyright:  2022-2023
!-->
<template>
  <div>
    <!-- 添加或修改文章管理对话框 -->
    <el-dialog
      :title="title"
      fullscreen
      custom-class="inner-dialog"
      :destroy-on-close="true"
      :visible.sync="dvShowArticleInfoDialog"
      :append-to-body="true"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row class="article-base-info-container">
          <el-col :span="6">
            <el-form-item label="封面图片">
              <image-upload
                @setImageUrl="setImageUrl"
                :limit="1"
                :file-size="10"
                :file-path="upload.path"
                :value="form.blogImage"
              />
            </el-form-item>
          </el-col>
          <el-col :span="18" class="row-content">
            <el-col :span="16">
              <el-form-item label="文章标题">
                <el-input v-model="form.blogTitle" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="文章分类">
                <treeselect
                  v-model="form.blogType"
                  :options="typeOptions"
                  :normalizer="normalizer"
                  :show-count="true"
                  placeholder="选择文章分类"
                />
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="标签">
                <div class="tag-form-item">
                  <el-select v-model="tagValues" multiple :multiple-limit="5" clearable filterable placeholder="请选择">
                    <el-option
                      v-for="item in tagList"
                      :key="item.id"
                      :label="item.tagName"
                      :value="item.id"
                    />
                  </el-select>
                  <span style="padding-left:2%;">
<!--                    <el-button icon="el-icon-plus" circle @click="openAddTagDialog"/>-->
                  </span>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="推荐等级">
                <el-select v-model="form.blogRecommend" placeholder="请选择推荐等级" clearable>
                  <el-option
                    v-for="dict in dicts.type.bl_recommend_level"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="文章来源">
                <el-radio-group v-model="form.original">
                  <el-radio
                    v-for="dict in dicts.type.bl_blog_original"
                    :key="dict.dictValue"
                    :label="dict.dictValue"
                  >{{ dict.dictLabel }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="文章出处">
                <el-input v-model="form.blogSource" placeholder="文章来源为转载时，请注明文章出处" :disabled="form.original === '1'" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="文章状态">
                <el-radio-group v-model="form.status">
                  <el-radio
                    v-for="dict in dicts.type.bl_blog_status"
                    :key="dict.dictValue"
                    :label="dict.dictValue"
                  >{{dict.dictLabel}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="评论状态">
                <el-radio-group v-model="form.commentOpen">
                  <el-radio
                    v-for="dict in dicts.type.sys_normal_disable"
                    :key="dict.dictValue"
                    :label="dict.dictValue"
                  >{{dict.dictLabel}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-col>
          <el-col :span="24">
            <el-form-item label="文章简介">
              <el-input v-model="form.blogRemark" type="textarea" :rows="2" placeholder="请输入简介" />
            </el-form-item>
            <el-divider content-position="left">文章内容</el-divider>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <TinyMceEditor v-model="form.blogContent"/>
          </el-col>
        </el-row>
      </el-form>

      <!-- 添加标签弹窗 -->
<!--      <el-dialog
        title="添加标签"
        :visible.sync="addTagDialog"
        :destroy-on-close="true"
        :modal-append-to-body="true"
        append-to-body
        width="500px"
        v-drag-zoom
      >
        <el-form ref="tagForm" :model="newTag" label-width="80px" >
          <el-row>
            <el-col :span="24">
              <el-form-item label="标签名">
                <el-input v-model="newTag.tagName" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注">
                <el-input v-model="newTag.remark" type="textarea" rows="3" placeholder="请输入内容" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" size="mini" @click="onAddTagSubmit">提交</el-button>
          <el-button size="mini" @click="closeAddTagDialog">取消</el-button>
        </div>
      </el-dialog>-->

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script lang="ts">
import { addBlog, getArticleInfo, updateBlog } from "@/api/blog/article";
import { getToken } from "@/utils/auth";
import { Vue, Component, Mixins, Prop } from "vue-property-decorator";
import { handleTree } from "@/utils/lemon";
import { queryAllTag } from "@/api/blog/tag";
import Treeselect from "@riophae/vue-treeselect"
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import TinyMceEditor from "@/components/Tinymce/TinyMceEditor.vue";
import ImageUpload from '@/components/ImageUpload/index.vue';
import mixin from "@/mixin/baseMixin";
import { listAllType } from "@/api/blog/type";
import { getDicts } from "@/api/system/dict/data";
import {mixins} from "vue-class-component";

@Component({
  components: { TinyMceEditor, Treeselect, ImageUpload }
})
export default class index extends mixins() {

  /** 文章id */
  @Prop()
  private articleId: any;

  private dvShowArticleInfoDialog: boolean =true

  /** 字典信息 */
  public dictArr: any = ['sys_normal_disable', 'bl_blog_status',
    'bl_blog_original', 'bl_recommend_level', 'bl_yes_no'];

  /** 数据字典信息 */
  public dicts: any = {
    type: {}
  };

  /** 弹出层标题 */
  public title: any = "";

  /** 上传文件的请求头 */
  public headers: any = {
    Authorization: getToken()
  };

  /** 上传图片回显 */
  public imageUrl: any = null;

  /** 控制添加标签弹窗显示 */
  public addTagDialog: any = false;

  /** 选中的标签 */
  public tagValues: any = [];

  /** 获取文章分类 */
  public typeList: any = [];

  /** 标签列表 */
  public tagList: any = [];

  /** 分类树选项 */
  public typeOptions: any = [];

  /** 上传文件路径 */
  public newTag: any = {
    id: null,
    tagName: '',
    remark: ''
  };

  /** 上传文件路径 */
  public upload: any = {
    // 是否禁用上传
    isUploading: false,
    // 设置上传的请求头部
    headers: { Authorization: "Bearer " + getToken() },
    // 上传的文件夹
    path: '/blog/blog-cover',
    // 上传的地址
    url: process.env.VUE_APP_BASE_API + "/file/file/upload"
  };

  /** 表单参数 */
  public form: any = {};

  /** 表单校验 */
  public rules: any = {
    blogTitle: [
      { required: true, message: "标题不能为空", trigger: "blur" }
    ],
    blogContent: [
      { required: true, message: "文章内容不能为空", trigger: "blur" }
    ],
    blogType: [
      { required: true, message: "文章分类不能为空", trigger: "change" }
    ],
    blogRecommend: [
      { required: true, message: "推荐等级不能为空", trigger: "blur" }
    ],
    commentOpen: [
      { required: true, message: "评论状态不能为空", trigger: "change" }
    ],
    original: [
      { required: true, message: "是否原创不能为空", trigger: "change" }
    ],
    status: [
      { required: true, message: "文章状态不能为空", trigger: "change" }
    ],
  }

  private async created() {
    await this.queryDictData();
    await this.getTypeList();
    await this.getTagList();
    await this.handleAddOrUpdate();
  }

  private mounted() {
    this.$nextTick(() => {
      const scrollEl:any = document.getElementsByClassName('el-dialog__body');
      if (scrollEl.length > 0) {
        const el = scrollEl[0];
        el.scrollTop = 0;
        document.addEventListener("scroll", this.handleScroll, true);
      }
    })
  }

  /** 销毁事件监听 */
  private beforeDestroy() {
    document.removeEventListener("scroll", this.handleScroll, true);
  }

  /** 转换菜单数据结构 */
  private normalizer(node: any) {
    if (node.children && !node.children.length) {
      delete node.children;
    }
    return {
      id: node.typeCode,
      label: node.typeName,
      children: node.children
    };
  }

  /** 查询文章管理列表 */
  private async getTypeList() {
    await listAllType().then(res => {
      const type = handleTree(res.data, "typeCode", "typeCodeP", null)
      type.forEach((e: any) => {
        this.typeOptions.push(e)
      })
    })
  }

  private async getTagList() {
    await queryAllTag().then((res: any) => {
      this.tagList = res.data
    })
  }

  /** 获取字典数据 */
  private async queryDictData() {
    for (const dictType of this.dictArr) {
      await getDicts(dictType).then((res: any) => {
        this.$set(this.dicts.type, dictType, res.data);
      });
    }
  }

  /** 修改按钮操作 */
  private async handleAddOrUpdate() {
    if ([undefined, null, ''].includes(this.articleId)) {
      this.imageUrl = null
      this.title = "添加文章";
    } else {
      getArticleInfo(this.articleId).then(response => {
        this.form = response.data;
        this.imageUrl = response.data.blogImage
        if (this.form.tagList != null) {
          this.form.tagList.forEach((e: any) => {
            this.tagValues.push(e.id)
          })
        }
        this.title = "修改文章";
      });
    }
  }

  /** 打开添加弹窗 */
  private openAddTagDialog() {
    if (this.tagValues.length < 5) {
      this.addTagDialog = true
    } else {
      this.$message.error('最多选择五个标签，请删除部分标签后操作')
    }
  }

  /** 关闭弹框 */
  private closeAddTagDialog() {
    // 关闭添加弹窗
    this.addTagDialog = false
  }
/*

  /!** 打开添加标签弹框 *!/
  private onAddTagSubmit() {
    addTag(this.newTag).then((res: any) => {
      this.$message.success(res.msg)
      this.getTagList()
      queryByTagName(this.newTag.tagName).then((res: any) => {
        this.tagValues.push(res.data.id)
        this.closeAddTagDialog()
      })
    })
  }
*/

  /** 回写图片地址 */
  private setImageUrl(url: string) {
    this.$set(this.form, 'blogImage', url);
  }

  /** 提交按钮 */
  private submitForm() {
    const formRef: any = this.$refs["form"];
    formRef.validate((valid: any) => {
      if (valid) {
        // 置空tagList
        this.form.tagList = []
        this.tagValues.forEach((e: any) => {
          const temp = { id: e, tagName: "", tagBlogCount: 0, createdTime: "", updateTime: "" };
          this.form.tagList.push(temp)
        })
        if (this.form.id != null) {
          updateBlog(this.form).then((response: any) => {
            this.$modal.msgSuccess(response.msg);
            this.$emit('hiddenArticleInfoDialog');
          });
        } else {
          addBlog(this.form).then((response: any) => {
            this.$modal.msgSuccess(response.msg);
            this.$emit('hiddenArticleInfoDialog');
          });
        }
      }
    });
  }

  /** 取消按钮 */
  public cancel() {
    this.$emit('hiddenArticleInfoDialog');
  }

  /** 编写滚动条事件 */
  private handleScroll() {
    // 获取滚动条元素对象
    const scrollEl:any = document.getElementsByClassName('el-dialog__body');
    if (scrollEl.length > 0) {
      const el = scrollEl[0];
      if (el !== null) {
        // 获取需要固定的元素对象
        const rightElArr = document.getElementsByClassName('tox-editor-header');
        if (rightElArr.length > 0) {
          let rightEl = rightElArr[0];
          const baseInfoEl = document.querySelector(".article-base-info-container");
          let btnUploadEl = document.querySelector(".editor-custom-btn-container");
          const topHeight = (baseInfoEl?.clientHeight || 0) + 23;
          // 判断滚动条的高度（大于380，给固定元素添加 class）
          if (el.scrollTop > topHeight) {
            rightEl.classList.add('tox-editor-header-fixed');
            if (btnUploadEl) {
              btnUploadEl.classList.add('editor-custom-btn-container-fixed');
            }
          } else {
            rightEl.classList.remove('tox-editor-header-fixed');
            if (btnUploadEl) {
              btnUploadEl.classList.remove('editor-custom-btn-container-fixed');
            }
          }
        }
      }
    }
  }
}
</script>
<style scoped lang="scss">
::v-deep .inner-dialog {
  .el-upload--picture-card,.el-upload-list__item {
    width: 230px !important;
    height: 138px !important;
  }
}
</style>
